package com.ftqh.security.oauth2.provider.code;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: Administrator
 * \* Date: 2017/1/9
 * \* Time: 14:01
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 */
public class RedisAuthorizationCodeServices extends RandomValueAuthorizationCodeServices {

    private static final String REDIS_AUTHORIZATION_CODE_KEY = "AUTHORIZATION_CODE";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    protected void store(String code, OAuth2Authentication authentication) {
        redisTemplate.boundHashOps(REDIS_AUTHORIZATION_CODE_KEY).put(code, authentication);
    }

    @Override
    protected OAuth2Authentication remove(String code) {
        OAuth2Authentication authentication;
        try {
            authentication = (OAuth2Authentication) redisTemplate.boundHashOps(REDIS_AUTHORIZATION_CODE_KEY).get(code);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
        if (authentication != null) {
            redisTemplate.boundHashOps(REDIS_AUTHORIZATION_CODE_KEY).delete(code);
        }
        return authentication;
    }
}
